DEBUG = 0

OPT = -O2#-flto

DEMO_DIR = ../../demo

COMMON_DIR = ../../common
COMMON_SRC = $(wildcard ../../common/*.c)

# C includes
DEMO_C_INCLUDES =     \
-I.              \
-I$(DEMO_DIR)    \
-I$(COMMON_DIR)   \
-Ilibsdl/include/SDL2


#######################################
# Compiler Setting
#######################################
PREFIX = aarch64-linux-
CC = $(PREFIX)gcc
AS = $(PREFIX)gcc -x assembler-with-cpp
CP = $(PREFIX)objcopy
AR = $(PREFIX)ar
SZ = $(PREFIX)size
OD = $(PREFIX)objdump
HEX =$(CP) -O ihex
BIN =$(CP) -O binary -S


LIB_DIR =

LIBS   = 

LIB_OPT =

CFLAGS := -Wall -std=c99  $(DEMO_C_INCLUDES)


ifeq ($(DEBUG), 1)
CFLAGS += -g -gdwarf-2 
endif


LDFLAGS = $(OPT) $(LIB_DIR) $(LIB_OPT) $(LIBS)

# default action: build all
all: button.exe arcbar.exe switch.exe


COMMON_OBJS = $(addprefix $(COMMON_DIR)/,$(notdir $(COMMON_SRC:.c=.o)))

SGL_DIR = ../../../source
# C sources
SGL_C_SOURCES =  \
$(wildcard $(SGL_DIR)/*.c)  \
$(wildcard $(SGL_DIR)/core/*.c)  \
$(wildcard $(SGL_DIR)/libs/*.c)  \
$(wildcard $(SGL_DIR)/libs/heap/*.c)  \
$(wildcard $(SGL_DIR)/draw/*.c)  \
$(wildcard $(SGL_DIR)/fonts/*.c)  \
$(wildcard $(SGL_DIR)/widget/*.c)  \

# C includes
SGL_C_INCLUDES =     \
-I.                 \
-I$(SGL_DIR)         \
-I$(SGL_DIR)/core    \
-I$(SGL_DIR)/libs    \
-I$(SGL_DIR)/libs/heap    \
-I$(SGL_DIR)/draw  \
-I$(SGL_DIR)/font   \
-I$(SGL_DIR)/widget   \


CFLAGS += $(SGL_C_INCLUDES)

SGL_BUILD_DIR := sgl_objs

SGL_OBJECTS += $(addprefix $(SGL_BUILD_DIR)/,$(notdir $(SGL_C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(SGL_C_SOURCES)))


button.exe: $(SGL_OBJECTS) $(COMMON_OBJS) $(DEMO_DIR)/src/button.o main.o
	@echo "Build $@"
	@$(CC) $^ $(LDFLAGS) -o $(DEMO_DIR)/$@

arcbar.exe: $(SGL_OBJECTS) $(COMMON_OBJS) $(DEMO_DIR)/src/arcbar.o main.o
	@echo "Build $@"
	@$(CC) $^ $(LDFLAGS) -o $(DEMO_DIR)/$@

switch.exe: $(SGL_OBJECTS) $(COMMON_OBJS) $(DEMO_DIR)/src/switch.o main.o
	@echo "Build $@"
	@$(CC) $^ $(LDFLAGS) -o $(DEMO_DIR)/$@


main.o: main.c
	$(CC) -c $(CFLAGS) $<  -o  $@

$(DEMO_DIR)/src/%.o : $(DEMO_DIR)/src/%.c
	@$(CC) -c $(CFLAGS) -MMD -MP \
		-MF  $(DEMO_DIR)/src/$(notdir $(<:.c=.d)) \
		-Wa,-a,-ad,-alms=$(DEMO_DIR)/src/$(notdir $(<:.c=.lst)) $< -o $@


$(COMMON_DIR)/%.o : $(COMMON_DIR)/%.c
	@$(CC) -c $(CFLAGS) -MMD -MP \
		-MF  $(COMMON_DIR)/$(notdir $(<:.c=.d)) \
		-Wa,-a,-ad,-alms=$(COMMON_DIR)/$(notdir $(<:.c=.lst)) $< -o $@


$(SGL_BUILD_DIR)/%.o: %.c Makefile | $(SGL_BUILD_DIR)
	@echo "CC $<"
	@$(CC) -c $(CFLAGS) -MMD -MP \
		-MF  $(SGL_BUILD_DIR)/$(notdir $(<:.c=.d)) \
		-Wa,-a,-ad,-alms=$(SGL_BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@


$(SGL_BUILD_DIR):
	mkdir $@


.PHONY: clean

clean:
	@rm -fR $(SGL_BUILD_DIR) \
			$(DEMO_DIR)/src/*.o $(DEMO_DIR)/src/*.d $(DEMO_DIR)/src/*.lst $(DEMO_DIR)/*.exe $(DEMO_DIR)/*.dll \
			$(COMMON_DIR)/*.o  $(COMMON_DIR)/*.lst $(COMMON_DIR)/*.d  ./*.o
